<template>
<div>
    <var-space>
        <var-button @click="transformFsDoc(feishuDoc)">
            转换
        </var-button>
    </var-space>
</div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import {feishuDoc,feishuApiResult} from '@/utils/docData.js'
const colorMap = {
  "rgb(216,57,49)": "tip",
};
const blockType ={
    'text':2,
    'ordered':13,
}

const numToBlockType ={
    '2':'text',
    '13':'ordered',
}
const findArrObj = (obj, cb) => {
  for (const [key, value] of Object.entries(obj)) {
    if (cb(value)) return value;
  }
};
//数字转字母
function numberToLetter(n) {
  return String.fromCharCode(n + 97);
}

const transformFsApi = (res) =>{
  console.log(res,feishuApiResult)
  const {data:{items}} = feishuApiResult;
  const itemsMap = items.reduce((result,item)=>{
    result.set(item.block_id,item)
    return result
  },new Map())
  const {content} = res;
  const newRes = content.map((item)=>{
    const {id,type} = item;
    if(['text','ordered_list','ordered_list_children'].includes(type)){
      const {block_type,...extra} = itemsMap.get(id);
      const {elements} = extra[numToBlockType[block_type]] ||{};
      const els = elements.map((item)=>{
        const {content,text_element_style:{bold}} = item['text_run'];
        return {
          text:content,
          style:{bold}
        }
      })
      return {
        type,
        els,
        seq:item.seq,
      }
    }else if(type==='image'){
      return {
        name:item.name,
        type
      }
    }else if(type==='imgList'){
      return {
        type,
        list:item.list
      }
    }else if(type.startsWith("heading")){
      const {text,...extra} = item;
      return {
        ...extra,
        els:[
          {
            text,
          }
        ]
      }
    }else{
      return {
        type,
        els:[
          {
            text:item.text,
          }
        ]
      }
    }

  })
  console.log({
    id:res.id,
    title:res.title,
    content:newRes,
  })
}

const transformFsDoc = (docData) => {
  const pageId = Object.keys(docData).find(
    (key) => docData[key].data.type === "page"
  );
  const pageData = docData[pageId].data;
  const transformResult = {
    id: pageId,
    title: pageData.text.initialAttributedTexts.text[0],
    content: [],
  };
  const seqMap = new Map();
  const calcSeq = (type, data) => {
    if (data.seq !== "auto") {
      const newSeq = Number(data.seq);
      seqMap.set(type, newSeq);
      return newSeq;
    }
    const seq = seqMap.get(type);
    if (!seq) {
      seqMap.set(type, 1);
      return 1;
    }
    seqMap.set(type, seq + 1);
    return seq + 1;
  };
  const hanOrderdChildren = (data) =>{
    const {children} = data;
    if (children?.length > 0) {
        children.forEach((itemId, index) => {
          const { id, data } = docData[itemId] || {};
          transformResult.content.push({
            id,
            type: "ordered_list_children",
            text: data.text.initialAttributedTexts.text[0],
            seq: `${numberToLetter(index)}.`,
          });
        });
    }
  }
  pageData.children.forEach((item, index) => {
    const { data } = docData[item];
    if (
      data.type === "text" &&
      !!data.text.initialAttributedTexts.text[0].length
    ) {
      const {
        text: {
          initialAttributedTexts: { text, attribs },
          apool: { numToAttrib },
        },
      } = data;
      let type = "text";
      const textHigthlight = findArrObj(
        numToAttrib,
        (arr) => arr[0] === "textHighlight"
      );
      if (textHigthlight) {
        type = colorMap[textHigthlight[1]] ?? "text";
      }
      transformResult.content.push({
        id: item,
        type,
        text: text[0],
      });
      hanOrderdChildren(data)
    } else if (data.type === "image") {
      const {
        image: { name, width, height, scale },
        type,
      } = data;
      transformResult.content.push({
        id: item,
        type,
        name: `${item}.${name.split(".").at(-1)}`,
        style: {
          width: width,
          height: height,
          scale: scale,
        },
      });
    } else if (data.type === "grid") {
      const imgList = [];
      data.children.forEach((gridId) => {
        docData[gridId].data.children.forEach((boxId) => {
          const { data, id } = docData[boxId];
          const {
            image: { name, width, height, scale },
            type,
          } = data;
          imgList.push({
            type,
            name: `${id}.${name.split(".").at(-1)}`,
            style: {
              width: width,
              height: height,
              scale: scale,
            },
          });
        });
      });
      transformResult.content.push({
        id: item,
        type: "imgList",
        list: imgList,
      });
    } else if (data.type === "ordered") {
      const {
        text: {
          initialAttributedTexts: { text, attribs },
          apool: { numToAttrib, nextNum },
        },
        parent_id,
        children,
      } = data;
      if (docData[parent_id].data.type !== "page") return;
      const obj = {
        id: item,
        type: "ordered_list",
        text: text[0],
      };
      if (data?.seq) {
        obj.seq = `${calcSeq(data.type, data)}.`;
      }
      transformResult.content.push(obj);
      hanOrderdChildren(data)
    } else if (!!data?.text) {
      const {
        text: {
          initialAttributedTexts: { text, attribs },
          apool: { numToAttrib },
        },
      } = data;
      if (text[0].length > 0) {
        const obj = {
          id: item,
          type: data.type,
          text: text[0],
        };
        if (data?.seq) {
          const seq = calcSeq(data.type, data);
          obj.seq =
            data.type === "heading1"
              ? `${seq}.`
              : `${seqMap.get("heading1")}.${seq}`;
        }
        transformResult.content.push(obj);
      }
    }
  });
  // console.log(pageData);
  // console.log("转换结果", transformResult);
  transformFsApi(transformResult)
};


</script>
<style scoped lang='less' >

</style>